using Website_Gateway.Data;
using Serilog;
using Serilog.Events;
using Volo.Abp.Data;

namespace Website_Gateway;

public class Program
{
    public async static Task<int> Main(string[] args)
    {
        var loggerConfiguration = new LoggerConfiguration()
#if DEBUG
            .MinimumLevel.Debug()
#else
            .MinimumLevel.Information()
#endif
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .WriteTo.Async(c => c.File("Logs/logs.txt"))
            .WriteTo.Async(c => c.Console());

        //if (IsMigrateDatabase(args))
        //{
        //    loggerConfiguration.MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning);
        //    loggerConfiguration.MinimumLevel.Override("Microsoft", LogEventLevel.Warning);
        //}

        Log.Logger = loggerConfiguration.CreateLogger();

        try
        {
            var builder = WebApplication.CreateBuilder(args);
            builder.Host.AddAppSettingsSecretsJson()
                .UseAutofac()
                .UseSerilog();
            //if (IsMigrateDatabase(args))
            //{
            //    builder.Services.AddDataMigrationEnvironment();
            //}
            //启动配置
            RunConfiguration(builder);
            await builder.AddApplicationAsync<Website_GatewayModule>();
            var app = builder.Build();
            await app.InitializeApplicationAsync();

            //if (IsMigrateDatabase(args))
            //{
            //    return 0;
            //}

            Log.Information("Starting Website_Gateway.");
            await app.RunAsync();
            return 0;
        }
        catch (Exception ex)
        {
            if (ex is HostAbortedException)
            {
                throw;
            }

            Log.Fatal(ex, "Website_Gateway terminated unexpectedly!");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    /// <summary>
    /// 启动配置
    /// </summary>
    private static void RunConfiguration(WebApplicationBuilder builder) 
    {
        #region  //网关配置 ocelot
        {
            // 加载 ocelot.json
            var conf = builder.Configuration["ASPNETCORE_ENVIRONMENT"];
            if (conf == "Development")
                builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
            else
                builder.Configuration.AddJsonFile($"ocelot.{conf}.json", optional: false, reloadOnChange: true);
        }
        #endregion
    }

    private static bool IsMigrateDatabase(string[] args)
    {
        return args.Any(x => x.Contains("--migrate-database", StringComparison.OrdinalIgnoreCase));
    }
}
